package com.noble.glamour.ui.agora.act.base;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.AppOpsManager;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;

import com.noble.glamour.R;
import com.noble.glamour.module.logic.application.ModuleMgr;
import com.noble.library.base.BaseActivity;
import com.noble.glamour.module.logic.baseui.custom.SimpleTipDialog;
import com.noble.glamour.module.util.PickerDialogUtil;
import com.noble.glamour.ui.agora.model.AgoraConstant;
import com.noble.glamour.ui.agora.model.EngineConfig;

import java.lang.reflect.Method;

/**
 * 音视频相关BaseActivity
 * <p>
 * Created by Su on 2017/6/27.
 */
public class RtcBaseActivity extends BaseActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        isCanBack(false);
        setCanNotify(false);
        super.onCreate(savedInstanceState);
        ModuleMgr.getRtcEnginMgr().initWorkerThread();
    }

    // 屏蔽回退按钮
    @Override
    public void onBackPressed() {
    }

    @Override
    protected boolean isImmersionBar() {
        return false;
    }

    /**
     * 获取引擎配置
     */
    protected final EngineConfig config() {
        return ModuleMgr.getRtcEnginMgr().getEngineConfig();
    }

    /**
     * 是否是特殊机型： 魅族、小米
     */
    private boolean isSpecial() {
        return "Xiaomi".equals(Build.MANUFACTURER)
                || "Meizu".equals(Build.MANUFACTURER);
    }

    /**
     * 手动检测悬浮窗权限
     */
    protected boolean checkOverLaysPermission() {
        // 小米魅族手机，去主动开启授权
        if (isSpecial()) {
            if (isFloatWindowOpAllowed()) return true;
            permissionAuth();
            return false;
        }

        // API22以下
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP_MR1) return true;

        if (!Settings.canDrawOverlays(this)) {
            permissionAuth();  // 未开启时，手动授权
            return false;
        }
        return true;
    }

    // 手动悬浮窗授权
    private void permissionAuth() {
        PickerDialogUtil.showSimpleAlertDialog(this, new SimpleTipDialog.ConfirmListener() {
            @Override
            public void onCancel() {
            }

            @Override
            public void onSubmit() {
                ModuleMgr.getRtcEnginMgr().setPermissionStatus(true);
                if (isSpecial()) {
                    openSetting();
                } else {
                    Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
                    startActivityForResult(intent, AgoraConstant.OVERLAY_PERMISSION_REQUEST_CODE);
                }
            }
        }, "请开启悬浮窗权限", R.color.text_zhuyao_black, "");
    }

    /**
     * 权限检测
     */
    private boolean checkSelfPermission(String permission, int requestCode) {
        if (ContextCompat.checkSelfPermission(this,
                permission)
                != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this,
                    new String[]{permission},
                    requestCode);
            return false;
        }

        if (Manifest.permission.CAMERA.equals(permission)) {
            ModuleMgr.getRtcEnginMgr().initWorkerThread();
        }
        return true;
    }

    /**
     * 权限动态申请结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case AgoraConstant.PERMISSION_REQ_ID_RECORD_AUDIO: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    checkSelfPermission(Manifest.permission.CAMERA, AgoraConstant.PERMISSION_REQ_ID_CAMERA);
                } else {
                    finish();
                }
                break;
            }

            case AgoraConstant.PERMISSION_REQ_ID_CAMERA: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, AgoraConstant.PERMISSION_REQ_ID_WRITE_EXTERNAL_STORAGE);
                    ModuleMgr.getRtcEnginMgr().initWorkerThread();
                } else {
                    finish();
                }
                break;
            }

            case AgoraConstant.PERMISSION_REQ_ID_WRITE_EXTERNAL_STORAGE: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 初始检测悬浮窗权限
                    checkSelfPermission(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, AgoraConstant.OVERLAY_PERMISSION_REQUEST_CODE);
                }
                break;
            }

            case AgoraConstant.OVERLAY_PERMISSION_REQUEST_CODE:
                ModuleMgr.getRtcEnginMgr().startRtcFloatService();
                break;
        }
    }

    /**
     * 魅族手机： 打开权限设置界面 ， 上面手动开启授权界面无效果？？？？
     */
    public void openSetting() {
        try {
            Intent localIntent = new Intent(
                    "miui.intent.action.APP_PERM_EDITOR");
            localIntent.setClassName("com.miui.securitycenter",
                    "com.miui.permcenter.permissions.AppPermissionsEditorActivity");
            localIntent.putExtra("extra_pkgname", getPackageName());
            startActivityForResult(localIntent, 11);

        } catch (ActivityNotFoundException localActivityNotFoundException) {
            Intent intent1 = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            Uri uri = Uri.fromParts("package", getPackageName(), null);
            intent1.setData(uri);
            startActivityForResult(intent1, 11);
        }
    }

    /**
     * 判断悬浮窗权限
     */
    @TargetApi(Build.VERSION_CODES.KITKAT)
    public boolean isFloatWindowOpAllowed() {
        final int version = Build.VERSION.SDK_INT;
        if (version >= 19) {
            return checkOp(24);  // AppOpsManager.OP_SYSTEM_ALERT_WINDOW
        } else {
            if ((getApplicationInfo().flags & 1 << 27) == 1 << 27) {
                return true;
            } else {
                return false;
            }
        }
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    public boolean checkOp(int op) {
        final int version = Build.VERSION.SDK_INT;

        if (version >= 19) {
            AppOpsManager manager = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE);
            try {

                Class<?> spClazz = Class.forName(manager.getClass().getName());
                Method method = manager.getClass().getDeclaredMethod("checkOp", int.class, int.class, String.class);
                int property = (Integer) method.invoke(manager, op,
                        Binder.getCallingUid(), getPackageName());
                if (AppOpsManager.MODE_ALLOWED == property) {
                    return true;
                } else {
                    return false;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ModuleMgr.getRtcEnginMgr().setPermissionStatus(false);
    }
}
